//
//  YMTargetType.swift
//  ChengLuMall
//
//  Created by 吳梓杭 on 2023/5/28.
//

import Moya

public enum YMRequestType: Int {
    case `default` = 0      /// 默认请求
    case uploadImage        /// 上传图片
    case uploadFile         /// 上传文件
}

public protocol YMTargetType: Moya.TargetType {
    
    /// 根路径地址
    var baseURL: URL { get }
    
    /// 请求api
    var path: String { get }
    
    /// 请求方式
    var method: YMMethod { get }
    
    /// 默认请求类型
    var requestType: YMRequestType { get }
    
    /// 图片
    var image: UIImage? { get }
    
    /// 图片文件压缩比 范围 (0.f ~ 1.f)
    var imageScale: CGFloat { get }
    
    /// 图片文件的类型,例:png、jpg(默认类型)....
    var imageType: String { get }
    
    // 文件
    var fileData: Data? { get }
    // 文件名
    var fileName: String { get }
    
    /// 是否忽略token
    var ignoreToken: Bool { get }
    
    /// 请求头
    var headers: [String : String]? { get }
    
    /// 设置网络请求参数的格式
    var encoding: YMParameterEncoding { get }
    
    /// 请求参数
    var parameters: YMParameters { get }
    
    /// 插件数组
    var plugins: APIPlugins { get }
    
    /// 请求失败后重新请求次数，默认0次
    var retry: Int { get }
    
    /// 请求超时
    var timeoutInterval: Double { get }
    
    // 数据是否需要解析
    var isParser: Bool { get }
    
    /// 调试环境是否禁止打印日志
    var isForbidPrint: Bool { get }
    
}

extension YMTargetType {
    
    /// 根路径地址
    public var baseURL: URL {
        return URL(string: kProGateway)!
    }
    
    /// 请求api
    public var path: String {
        return ""
    }
    
    /// 请求方式
    public var method: YMMethod {
        return YMNetworkConfig.method
    }
    
    /// 默认请求类型
    public var requestType: YMRequestType {
        return .default
    }
    
    /// 图片
    public var image: UIImage? {
        return UIImage()
    }
    
    /// 图片文件压缩比 范围 (0.f ~ 1.f)
    public var imageScale: CGFloat {
        return 0.3
    }
    
    /// 图片文件的类型,例:png、jpg(默认类型)....
    public var imageType: String {
        return ""
    }
    
    // 文件
    public var fileData: Data? {
        return Data()
    }
    
    // 文件名
    var fileName: String {
        let timeInterval = NSDate.now.timeIntervalSince1970
        let data = Data((0..<3).map { _ in UInt8.random(in: 0...255) })
        let randomString = data.base64EncodedString().prefix(4)
        let fileName = "\(String(format: "%1.0f",timeInterval))\(randomString)"
        return fileName
    }
    
    /// 是否忽略token
    public var ignoreToken: Bool {
        return false
    }
    
    /// 请求头
    public var headers: [String : String]? {
        var headers = [String : String]()
//        if !self.ignoreToken {
//            headers["token"] = YMUserConfig.accountToken
//        }
//        headers["platform"] = "ios"
        return headers
    }
    
    /// 设置网络请求参数的格式
    public var encoding: YMParameterEncoding {
        switch self.method {
        case .get:
            return URLEncoding.default
        case .post:
            return JSONEncoding.default
        default:
            return JSONEncoding.default
        }
    }
    
    /// 从第几页开始
    public var page: Int {
        return 1
    }
    
    /// 一次性加载多少个
    public var size: Int {
        return YMNetworkConfig.size
    }
    
    /// 请求参数
    public var parameters: YMParameters {
        return [:]
    }
    
    public var plugins: APIPlugins {
        return []
    }
    
    /// 请求失败后重新请求次数，默认0次
    public var retry: Int {
        return 0
    }
    
    /// 请求超时
    public var timeoutInterval: Double {
        return YMNetworkConfig.timeoutInterval
    }
    
    // 数据是否需要解析
    public var isParser: Bool {
        return true
    }
    
    /// 是否禁止打印日志
    public var isForbidPrint: Bool {
        return false
    }
    
    public var task: Moya.Task {
        switch self.requestType {
        case .uploadFile:
            // 创建MultipartFormData数组
            var array = [Moya.MultipartFormData]()
            
            // 添加文件数据
            if let fileData = self.fileData {
                // 获取文件扩展名
                let fileExtension = (self.fileName as NSString).pathExtension
                // 获取MIME类型
                let mimeType = getMimeType(for: fileExtension)
                
                let formData = Moya.MultipartFormData(
                    provider: .data(fileData),
                    name: "file",
                    fileName: fileName,
                    mimeType: mimeType
                )
                array.append(formData)
            }
            return .uploadCompositeMultipart(array, urlParameters: self.parameters)
        case .uploadImage:
            var array = [Moya.MultipartFormData]()
            let image = self.image ?? UIImage()
            let imageData = image.jpegData(compressionQuality: self.imageScale)
            let timeInterval = NSDate.now.timeIntervalSince1970
            let imageType = !self.imageType.isEmpty ? self.imageType : "jpg"
            let data = Data((0..<3).map { _ in UInt8.random(in: 0...255) })
            let randomString = data.base64EncodedString().prefix(4)
            let imageFileName = "\(String(format: "%1.0f",timeInterval))\(randomString)-width_\(String(format: "%1.0f", image.size.width))-height_\(String(format: "%1.0f", image.size.height)).\(imageType)"
            let formData = Moya.MultipartFormData(provider: .data(imageData ?? Data()), name: "file", fileName: imageFileName, mimeType: imageType)
            array.append(formData)
            return .uploadCompositeMultipart(array, urlParameters: self.parameters) 
        default:
            return .requestParameters(parameters: self.parameters, encoding: self.encoding)
        }
    }
    
    // 辅助方法：根据文件后缀获取MIME类型
    private func getMimeType(for fileExtension: String) -> String {
        let mimeTypes = [
            // 图片类型
            "jpg": "image/jpeg",
            "jpeg": "image/jpeg",
            "png": "image/png",
            "gif": "image/gif",
            "heic": "image/heic",      // iPhone 照片格式
            "heif": "image/heif",      // High Efficiency Image Format
            "webp": "image/webp",
            
            // 视频类型
            "mp4": "video/mp4",
            "mov": "video/quicktime",  // iPhone 默认视频格式
            "m4v": "video/x-m4v",
            "avi": "video/x-msvideo",
            
            // 音频类型
            "mp3": "audio/mpeg",
            "m4a": "audio/mp4",
            "aac": "audio/aac",
            "wav": "audio/wav",
            
            // 文档类型
            "pdf": "application/pdf",
            "doc": "application/msword",
            "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            "xls": "application/vnd.ms-excel",
            "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "ppt": "application/vnd.ms-powerpoint",
            "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
            "txt": "text/plain",
            "rtf": "application/rtf",
            
            // 苹果特有格式
            "pages": "application/vnd.apple.pages",      // Pages 文档
            "numbers": "application/vnd.apple.numbers",  // Numbers 文档
            "key": "application/vnd.apple.keynote",      // Keynote 文档
            "ipa": "application/x-itunes-ipa",           // iOS 应用
            "plist": "application/x-plist",             // 属性列表文件
            
            // 其他常见类型
            "zip": "application/zip",
            "rar": "application/x-rar-compressed",
            "json": "application/json",
            "xml": "application/xml",
            "html": "text/html",
            "css": "text/css",
            "js": "application/javascript"
        ]
        
        return mimeTypes[fileExtension.lowercased()] ?? "application/octet-stream"
    }
}
